<?php

namespace app\admin\service;


use app\admin\model\DeviceBind;
use app\admin\model\DeviceImei;
use app\admin\model\DeviceModel;
use think\Db;

/**
 * 设备列管理-服务类
 * Class DeviceImeiService
 * @package app\admin\service
 */
class DeviceImeiService extends BaseService
{
    /**
     * 构造函数
     */
    public function __construct()
    {
        $this->model = new DeviceImei();
    }

    /**
     * 获取数据列表
     */
    public function getList()
    {
        $param = request()->param();

        // 查询条件
        $map = [];
        $sort = 'id desc';
        $is_sql = 0;


        if (!empty($param['imei'])) {
            $map[] = ['imei', 'like', '%' . $param['imei'] . '%'];
        }
        if (!empty($param['rfid'])) {
            $map[] = ['rfid', 'like', '%' . $param['rfid'] . '%'];
        }
        if (!empty($param['ip'])) {
            $map[] = ['ip', 'like', '%' . $param['ip'] . '%'];
        }
        if (!empty($param['model_id'])) {
            $map[] = ['model_id', '=', $param['model_id']];
        }
        if (!empty($param['mac'])) {
            $map[] = ['mac', 'like', '%' . $param['mac'] . '%'];
        }
        if (!empty($param['ver'])) {
            $map[] = ['ver', 'like', '%' . $param['ver'] . '%'];
        }
        // 是否活跃
        $is_active = isset($param['is_active']) ? (int)$param['is_active'] : 0;
        if ($is_active) {
            $map[] = ['is_active', '=', $is_active];
        }

        // 是否禁止
        $is_forbid = isset($param['is_forbid']) ? (int)$param['is_forbid'] : 0;
        if ($is_forbid) {
            $map[] = ['is_forbid', '=', $is_forbid];
        }

        //获取数据总数
        $count = $this->model->where($map)->count();
        // 打印SQL
        if ($is_sql) {
            echo $this->model->getLastSql();
        }
        $list = [];
        if ($count > 0) {
            $list = $this->model
                ->with('deviceModel')
                ->where($map)
                ->order($sort)
                ->page(PAGE, PERPAGE)
                ->field('update_time,delete_time', true)
                ->select();
        }

        //返回结果
        return array(
            "msg" => '操作成功',
            "code" => 0,
            "data" => $list,
            "count" => $count,
        );

    }


    public function edit()
    {
        // 参数
        $param = request()->param();

        $imei = getter($param, "imei");
        if (empty($imei)) {
            return message("imei不能为空", false);
        }
        if(input('id')){
            $where = ['imei'=> $imei];
            $id = getter($param, "id");
            $where['id'] = ['<>',$id];
            $count = $this->model->where($where)->count();
            if ($count) {
                return message("imei已存在", false);
            }
        }else{
            $where = ['imei'=> $imei];
            $count = $this->model->where($where)->count();
            if ($count) {
                return message("imei已存在", false);
            }
        }
        return parent::edit();
    }


    public function delete()
    {
        // 参数
        $param = request()->param();
        // 记录ID
        $ids = getter($param, "id");
        if (empty($ids)) {
            return message("记录ID不能为空", false);
        }
        $ids = (array)$ids;
        foreach ($ids as $id) {
            $imei = $this->model->where('id', $id)->value('imei');
            $count = DeviceBind::where('imei',$imei)->count();
            if ($count) {
                return message("IMEI：$imei 已绑定，请先解绑再删除", false);
            }
        }


        //$result = DeviceImei::destroy($ids,true);
        if(is_array($ids)){
            foreach ($ids as $id) {
                Db::table('think_device_imei')->where('id',$id)->delete();
            }
        }else{
           Db::table('think_device_imei')->where('id',$ids)->delete();
        }
      /*  if (!$result) {
            return message("删除失败", false);
        }*/
        return message("删除成功");
    }


    public function setForbid()
    {
        // 参数
        $is_forbid = request()->param('is_forbid/d');
        $id = request()->param('id/d');
        // 记录ID
        if (empty($id)) {
            return message("记录ID不能为空", false);
        }
        if (!in_array($is_forbid, [0, 1])) {
            return message("参数错误", false);
        }
        $bind = DeviceBind::get($id);
        if (empty($bind)) {
            return message("数据不存在", false);
        }
        $row = DeviceImei::get(['imei'=>$bind->imei]);
        if (empty($row)) {
            return message("设备imei不存在", false);
        }
        $row->is_forbid = $is_forbid;
        $result = $row->save();
        if (!$result) {
            return message("失败", false);
        }
        return message("成功");
    }

    public function setQueryStatus()
    {
        // 参数
        $status = request()->param('status/d');
        $id = request()->param('id/d');
        // 记录ID
        if (empty($id)) {
            return message("记录ID不能为空", false);
        }
        if (!in_array($status, [0, 1])) {
            return message("参数错误", false);
        }
        $row = DeviceImei::get($id);
        if (empty($row)) {
            return message("数据不存在", false);
        }
        $row->query_status = $status;
        $result = $row->save();
        if (!$result) {
            return message("失败", false);
        }
        return message("成功");
    }


    /**
     * 导入Excel
     */
    public function importExcel()
    {
        $error = "";
        // 上传文件(非图片)
        $result = upload_file('file', 'imei/import/', $error);
        if (!$result) {
            return message($error, false);
        }
        // 文件路径
        $filePath = FILE_PATH . $result;
        if (!file_exists($filePath)) {
            return message("文件不存在", false);
        }
        // 读取文件
        $objPHPExcel = \PHPExcel_IOFactory::load($filePath); //获取sheet表格数目
        $sheetSelected = 0;
        $objPHPExcel->setActiveSheetIndex($sheetSelected); //获取表格行数
        $activeSheet = $objPHPExcel->getActiveSheet();
        $rowCount = $activeSheet->getHighestRow(); //获取表格列数
        $columnCount = $activeSheet->getHighestColumn();
        $totalNum = $rowCount - 1;
        $dataArr = array();
        // 循环读取行数据
        for ($row = 2; $row <= $rowCount; $row++) {
            // 获取列值
            $imei = $activeSheet->getCell("A" . $row)->getValue();
            $imei_id = $this->model->where(['imei' => $imei])->value('id');
            if ($imei_id) {
                return message(sprintf('第%s行，设备IMEI：%s已存在', $row, $imei), false);
            }
            $rfid = $activeSheet->getCell("B" . $row)->getValue() ?: '';
            $ip = $activeSheet->getCell("C" . $row)->getValue();
            $model_name = trim($activeSheet->getCell("D" . $row)->getValue());

            $model_id = DeviceModel::where(['name' => $model_name])->value('id');
            if (empty($model_id)) {
                return message(sprintf('第%s行，型号：%s不存在', $row, $model_name), false);
            }
            $mac = $activeSheet->getCell("E" . $row)->getValue();
            $ver = $activeSheet->getCell("F" . $row)->getValue();

            $dataArr[] = compact('imei', 'rfid', 'ip', 'model_id', 'mac', 'ver');
        }

        Db::startTrans();
        try {
            $this->model->saveAll($dataArr);
            Db::commit();
        } catch (\Throwable $e) {
            Db::rollback();
            trace('导入设备imei异常：' . $e->getTraceAsString(), 'error');
            return message($e->getMessage(), false);
        }
        return message("本次成功导入{$totalNum}条数据", true);
    }


    /**
     * 导出Excel
     * @throws \PHPExcel_Exception
     * @throws \PHPExcel_Reader_Exception
     * @throws \PHPExcel_Writer_Exception
     */
    public function exportExcel()
    {
        // 获取导出的数据源
        $res = $this->getList();
        $list = $res['data'];

        // 实例化PHPExcel类
        $objPHPExcel = new \PHPExcel();
        // 激活当前的sheet表
        $activeSheet = $objPHPExcel->setActiveSheetIndex(0);
        //5.设置表格头（即excel表格的第一行）
        $activeSheet->setCellValue('A1', 'IMEI')
            ->setCellValue('B1', 'RFID')
            ->setCellValue('C1', '服务IP')
            ->setCellValue('D1', '型号')
            ->setCellValue('E1', '蓝牙MAC')
            ->setCellValue('F1', '版本号');
        //设置列水平居左
        $activeSheet->getStyle('A')->getAlignment()
            ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_LEFT);
        $activeSheet->getStyle('B')->getAlignment()
            ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_LEFT);
        $activeSheet->getStyle('C')->getAlignment()
            ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_LEFT);
        $activeSheet->getStyle('D')->getAlignment()
            ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_LEFT);
        $activeSheet->getStyle('E')->getAlignment()
            ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_LEFT);
        $activeSheet->getStyle('F')->getAlignment()
            ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_LEFT);

        // 设置单元格宽度
        $activeSheet->getColumnDimension('A')->setWidth(20);
        $activeSheet->getColumnDimension('B')->setWidth(20);
        $activeSheet->getColumnDimension('C')->setWidth(20);
        $activeSheet->getColumnDimension('D')->setWidth(20);
        $activeSheet->getColumnDimension('E')->setWidth(20);

        // 循环刚取出来的数组，将数据逐一添加到excel表格。
        for ($i = 0; $i < count($list); $i++) {
            $activeSheet->setCellValue('A' . ($i + 2), $list[$i]['imei']);
            $activeSheet->setCellValue('B' . ($i + 2), $list[$i]['rfid']);
            $activeSheet->setCellValue('C' . ($i + 2), $list[$i]['ip']);
            $activeSheet->setCellValue('D' . ($i + 2), $list[$i]['model_name']);
            $activeSheet->setCellValue('E' . ($i + 2), $list[$i]['mac']);
            $activeSheet->setCellValue('F' . ($i + 2), $list[$i]['ver']);
        }
        // 设置保存的Excel表格名称
        $filename = '设备IMEI_' . date('YmdHis', time()) . ".xlsx";
        // 设置当前激活的sheet表格名称
        $activeSheet->setTitle('设备IMEI');
        // 保存本地文件
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
        $savePath = UPLOAD_TEMP_PATH . "/" . $filename;
        $objWriter->save($savePath);

        // 文件地址
        $filePath = get_image_url(str_replace(PUBLIC_PATH, "", $savePath));
        return message("操作成功", true, $filePath);
    }

}

